<?php
/**
 * Allows forwarding of log messages to a client-side console.
 */
class Console
{
	/**
	 * Events below this level will not be shown in the console.
	 */
	static public $minLevel = Event::LOG_DEBUG;
	
	/**
	 * Initializes the console for regular web/html-based operation.
	 */
	static public function initClientConsole()
	{
		Client::addLibrary('modules/console/firebug/firebug.js');
		Event::addListener('shutdown', array('Console', 'sendConsole'));
		
		Event::addListener('log', array('Console', 'log'));
		Event::deactivateStartupMode();
	}
	
	/**
	 * Initializes the console for use during an AJAX request.
	 */
	static public function initAjaxMode()
	{
		Event::addListener('shutdown', array('Console', 'sendConsoleAjax'));
		
		Event::addListener('log', array('Console', 'log'));
		Event::deactivateStartupMode();
		
		self::$minLevel = Event::LOG_WARN;
	}
	
	/**
	 * Send the console output back to the client.
	 * 
	 * Called automatically as a shutdown handler! You do not need to call this.
	 */
	static public function sendConsole()
	{
		echo '<script>';
		foreach (self::$log as $log) {
			echo self::getCommand($log);			
		}
		echo '</script>';
	}
	
	/**
	 * Add the console output to an AJAX response
	 */
	static public function sendConsoleAjax()
	{
		$consoleCommand = '';
		foreach (self::$log as $log) {
			$consoleCommand .= self::getCommand($log) . "\r\n";			
		}
		
		Ajax::$data['console'] = $consoleCommand;
	}
	
	static protected function getCommand($log)
	{
		if ($log['level'] < self::$minLevel) return '';
		
		switch ($log['level']) {
			case Event::LOG_ERROR:
				$cmd = 'console.error';
				break;
			case Event::LOG_WARN:
				$cmd = 'console.warn';
				break;
			case Event::LOG_INFO:
				$cmd = 'console.info';
				break;
			case Event::LOG_DEBUG:
			default:
				$cmd = 'console.info';
		}
		
		return $cmd.'("'.self::format_time($log['timestamp']).' ['.$log['component'].'] '.addslashes($log['message']).'");';
	}
	
	static protected $log = array();
	/**
	 * This is the handler to pass in log messages.
	 * 
	 * Do not call this yourself, use Event::log() instead!
	 *
	 * @param array $data Event data.
	 */
	static public function log($data)
	{
		self::$log[] = $data;
	}
	
	static protected function format_time($time)
	{
		return sprintf('%12s', sprintf('%.6f', $time)); 
	}
}

?>